<template>
  <!-- 上传合同 -->
  <el-dialog
    v-model="dialogVisible"
    title="上传合同"
    width="30%"
    :before-close="handleClose"
  >
    <el-form
      v-loading="loading"
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      size="large"
      label-position="top"
      status-icon
    >
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="合同模板">
            <c-file-upload disabled v-model="ruleForm.templateList" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传合同" prop="files">
            <c-file-upload v-model="ruleForm.files" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button size="large" :loading="buttonLoading" @click="handleClose">取消</el-button>
      <el-button size="large" :loading="buttonLoading" type="primary" @click="handleSubmit"> 确认 </el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import cFileUpload from "@/components/Upload/FileUpload.vue";
import {ElMessage} from 'element-plus'
const { proxy } = getCurrentInstance();
const emits = defineEmits(["change"]);
const dialogVisible = ref(false);
const ruleFormRef = ref();
const ruleForm = ref({
  templateList: [],
  files: [],
});
const loading = ref(false);
const buttonLoading = ref(false);
const handleOpen = (item) => {
  loading.value = true;
  const url = "/sellerCarInApply/getById";
  const params = {
    id: item.id,
  };
  ruleForm.value.id = item.id;
  proxy.$get({ url, params }).then((res) => {
    (res.contractList || []).forEach((x) => {
      // type 	合同分类：0-模板，1-正式
      if (x.type === 0) {
        ruleForm.value.templateList.push(x.url);
      } else if (x.type === 1) {
        ruleForm.value.files.push(x.url);
      }
    });
    loading.value = false;
  });
  dialogVisible.value = true;
};
const handleSubmit = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true
      const url = "/sellerContract/formal/upload";
      proxy.$post({ url, data: ruleForm.value }).then((res) => {
        ElMessage.success('操作成功')
        emits("change");
        buttonLoading.value = false
        handleClose()
      },()=>{
        buttonLoading.value = false
      });
    }
  });
};
const handleClose = () => {
  ruleForm.value = {
    id: null,
    templateList: [],
    files: [],
  };
  ruleFormRef.value.resetFields();
  dialogVisible.value = false;
};
const rules = ref({
  files: [
    {
      type: "array",
      required: true,
      message: "请选择合同",
      trigger: "change",
    },
  ],
});
defineExpose({
  handleOpen,
});
</script>
